/*jslint sloppy: true */
/*global require */
var angular = require('angular');
var probe = require('../global');
probe.controller('Master', function ($scope, ocDI, LC, $element, ocDialog, $location, cmd) {
	var LCF, cmdIndex = 0,
		cmdHistory = [],
		globalCase = LC.Case(),
		bootMode = $location.search().panel,
		cmdForm = $element[0].querySelector('#console');


	ocDI.setTitleButton('仿真测试', {
		icon: 'simulation',
		fn: function () {
			$scope.setMode('case');
		}
	});
	$scope.setMode = function (mode) {
		$location.search('panel', mode);
		$scope.mode = mode;
	};

	if ($scope.bootSetup.mode === 'full') {
		ocDI.setTitleButton('测试任务', {
			icon: 'taskmode',
			fn: function () {
				$scope.setMode('task');
			}
		});
	} else if ($scope.bootSetup.mode === 'trial') {
		setTimeout(function () {
			ocDialog.alert({
				title: '试用模式',
				message: '此次启动您未指定链接到合法的项目，\n只能使用测试用例编辑的部分功能。'
			}, ocDI);
		}, 200);
	}

	LC.init($element[0].querySelector('div#project'), function () {
		$scope.LCF = LCF = this;
		angular.element(this)
			.css({ width: '100%', height: '100%', border: 'none' })
			.attr('src', $scope.project.probeOrigin || '/');
	});
	$scope.fullScreen = function () {
		angular.element(LCF).css({ width: '100%', height: '100%' });
	};
	$scope.screen = {
		width: function (newWidth) {
			if (angular.isDefined(newWidth)) {
				LCF.style.width = newWidth.match(/\d+/)[0] + 'px';
			}
			return LCF.offsetWidth;
		},
		height: function (newHeight) {
			if (angular.isDefined(newHeight)) {
				LCF.style.height = newHeight.match(/\d+/)[0] + 'px';
			}
			return LCF.offsetHeight;
		}
	};


	$scope.isConsoleShow = false;
	$scope.commandText = '';
	$scope.cmdIn = function () {
		var t, cmd = $scope.commandText;

		if (!cmd) { return; }
		cmdIndex = cmdHistory.push(cmd);
		$scope.cmdOut(cmd, 'cmd-in');

		try {
			t = LC.parseAt(cmd);
			LC.Instruction(t.TYPE).$new(t, globalCase).execute();
		} catch (e) {
			$scope.cmdOut('Bad command', 'danger')
		}

		$scope.commandText = '';
	};
	$scope.cmdOut = function (message, level) {
		var inner = cmdForm.querySelector('.oc-list-inner'),
			isAutoScroll = inner.scrollTopMax === inner.scrollTop;
		cmd.push(message, level);
		if (isAutoScroll) {
			setTimeout(function () {
				inner.scrollTo(0, inner.scrollTopMax);
			}, 10);
		}
	};
	$scope.revertCmd = function (e) {
		if (e.keyCode === 38) { // up
			if (cmdIndex === 0) { return; }
			$scope.commandText = cmdHistory[cmdIndex -= 1];
		} else if (e.keyCode === 40) { // down
			if (cmdIndex === cmdHistory.length - 1) { return; }
			$scope.commandText = cmdHistory[cmdIndex += 1];
		}
	};

	//init
	$scope.setMode(bootMode || 'case');
});
